<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/26
 * Time: 16:16
 */

namespace app\api\controller;


use app\common\controller\Api;
use think\Cache;
use think\Db;
use think\Exception;
use think\session\driver\Redis;
/*
 *商品类接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $token = '';
    protected $userid = '';

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        $this->token = $_REQUEST["token"]??'';
        if ($this->token){
            $this->userid = Db::name("user_token")->where("token",'eq',$this->token)->value("user_id");
        }
    }
    /**
     * 品牌分类
     * @ApiTitle    (品牌分类)
     * @ApiSummary  (品牌分类
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Gouwu/goodCates)
     * @ApiHeaders  (name=brand_id, type=int, required=false, description="品牌id")
     * @ApiHeaders  (name=limit, type=int, required=false, description="条数")
     * @ApiHeaders  (name=page, type=int, required=false, description="页码")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function goodCates(){
        $brand_id =  $_REQUEST['brand_id']??0;
        $brandLists = Db::name("brand")
            ->where("pid",$brand_id)
            ->select();
//        if (empty($brand_id)){
            foreach ($brandLists as &$value){
//                $list = Db::name("brand")
//                    ->where("pid",$value['id'])
//                    ->select();
                $goods = Db::name("goods")
                    ->field("id,image,goods_name")
                    ->where("brand_id",$value['id'])
                    ->select();
//                $list[0]['goodslist'] = $goods;
                $value['childlist'] = $goods;
                break;
            }
//        }
        if ($brandLists){
            $this->success('操作成功',$brandLists);
        }else{
            $this->success("暂无数据");
        }

    }
    /**
     * 获取品牌下的商品分类列表
     * @ApiTitle    (获取品牌下的商品分类列表)
     * @ApiSummary  (获取品牌下的商品分类列表）
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Gouwu/goodsLists)
     * @ApiHeaders  (name=brand_id, type=int, required=false, description="品牌id")
     * @ApiHeaders  (name=limit, type=int, required=false, description="条数")
     * @ApiHeaders  (name=page, type=int, required=false, description="页码")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function goodsLists(){
        $brand_id =  $_REQUEST['brand_id']??'';
        $order =  $_REQUEST['order']??1;//1 默认排序 2价格低到高 3价格高到低
        if ($order == 2){
            $orderRule = 'new_price asc';
        }else if ($order == 3){
            $orderRule = 'new_price desc';
        }else{
            $orderRule = 'order asc';
        }
        if (empty($brand_id)){
            $this->error('操作异常');
        }
        $list = Db::name("goods")
            ->where("brand_id",$brand_id)
            ->order($orderRule)
            ->select();
        if ($list){
            $this->success('操作成功',$list);
        }else{
            $this->success("暂无数据");
        }

    }
    /**
     * 商品详情
     * @ApiTitle    (商品详情)
     * @ApiSummary  (商品详情）
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Gouwu/goodsDetail)
     * @ApiHeaders  (name=goods_id, type=int, required=false, description="商品id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function goodsDetail(){
        $goods_id =  $_REQUEST['goods_id']??'';

        if (empty($goods_id)){
            $this->error('操作异常');
        }

        $list = Db::name("goods")
            ->where("id",$goods_id)
            ->find();
        $images = explode(',',$list['images']);
        $list['imgUrls'] = $images;
        //是否收藏过该商品
        if ($this->userid){
            $data['user_id'] = $this->userid;
            $data['goods_id'] = $goods_id;
            if (Db::name("collect_goods")->where($data)->find()){
                $list['is_collect'] = 1;
            }else{
                $list['is_collect'] = 0;
            }

        }else{
            $list['is_collect'] = 0;
        }
        //获取参数配置
        $service = Db::name("service")->order("order asc")->select();
        $list['service'] = $service;

        //获取推荐商品
        $tablePre = config('database.prefix');
        $sql = "SELECT * FROM `".$tablePre."goods` WHERE brand_id IN (SELECT brand_id FROM `".$tablePre."goods` WHERE id=$goods_id) AND id != $goods_id ORDER BY RAND() LIMIT 4";
        $res = Db::query($sql);
        $list['recommend'] = $res;
        //获取评价列表
        $list['appraise'] = $this->goodsAppraise(1);
        $list['appraiseCount'] = Db::name("appraise")->where("goods_id",$list['id'])->count();
        $this->success('操作成功',$list);
    }
    /**
     * 商品评价列表
     * @ApiTitle    (商品评价列表)
     * @ApiSummary  (商品评价列表）
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Gouwu/goodsAppraise)
     * @ApiHeaders  (name=goods_id, type=int, required=false, description="商品id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function goodsAppraise($limit=3,$flag=0){
        $tmp = $_REQUEST['limit']??'';
        if ($tmp){
            $limit = $tmp;
        }

        $goods_id = $_REQUEST['goods_id']??'';
        if (!$goods_id){
            $this->error("参数异常");
        }
        $list = Db::name("appraise")
            ->alias("a")
            ->join("user u","u.id=a.user_id")
            ->join("order o","o.id=a.order_id")
            ->field("a.*,u.avatar,u.nickname,o.chicun_id")
            ->where("a.goods_id",$goods_id)
            ->where("a.is_pass",1)
            ->order("a.create_time desc")
            ->limit($limit)
            ->select();
        foreach ($list as &$value){
            $value['createtime'] = date("Y年m月d日 H:i:s",$value['create_time']);
            $chicun = Db::name("chicun")->where("id","in",$value['chicun_id'])->field("name")->select();
            $arr = [];
            foreach ($chicun as &$va){
                $arr[] = $va['name'];
            }
            $value['chicun'] = implode(',',$arr);
        }
        if (!$flag){
            $this->success('操作成功',$list);
        }else{
            return $list;
        }
    }


}